/*
 * @Author: your name
 * @Date: 2021-10-06 17:34:50
 * @LastEditTime: 2021-10-09 17:55
 * @LastEditors: xinyang3
 * @Description: file save and delete
 * @FilePath: \blog\bgmg\util\doc-save.js
 */
const fs = require('fs');
const path = require('path');
const format = require('./date-fmt');

const server_file_path = path.resolve(__dirname, '../md_docs/');

function saveFile(file) {
  const date = new Date();
  const fileName =
    format(date, 'yyyy-MM-dd') +
    '_' +
    date.getTime() +
    // '_' +
    // Math.ceil(Math.random() * 10000) +
    '_' +
    file.name;
  if (!fs.existsSync(server_file_path)) {
    fs.mkdirSync(server_file_path);
  }
  const filePath = path.resolve(server_file_path, fileName);

  const reader = fs.createReadStream(file.path);
  const writer = fs.createWriteStream(filePath);
  reader.pipe(writer);
  console.debug(`uploading ${file.name} -> ${filePath}`);
  return Promise.resolve({ path: filePath, fileName: fileName });
}

/**
 * @description: 文件重命名保存在 md_doc目录下
 * @param {*} file
 * @return {*}
 */
function saveFileAsync(file) {
  let file_origin_name = file.name,
    ext = file_origin_name.substr(file_origin_name.lastIndexOf('.')),
    // num = Math.ceil(Math.random() * 10000);
    times = new Date().getTime();
  const new_file_name = `note-${times}${ext}`;

  return new Promise((resolve, reject) => {
    try {
      const file_path = path.resolve(server_file_path, new_file_name);
      fs.open(file_path, 'wx', (e, fd) => {
        if (e) {
          console.debug(`file ${file_path} has exist.`);
          return reject();
        }

        const reader = fs.createReadStream(file.path);
        const writer = fs.createWriteStream(file_path);
        reader.pipe(writer);
        console.debug(`file has upload. file is ${new_file_name}`);

        resolve({ file_path, file_name: new_file_name, file_origin_name });
      });
    } catch (error) {
      console.debug(error);
      reject();
    }
  });
}
/**
 * @description: 删除文件
 * @param {*} file_name
 * @param {*} file_path
 * @return {*}
 */
function deleteFile({ file_name, file_path }) {
  const file = path.resolve(server_file_path, file_name);
  return new Promise((resolve, reject) => {
    try {
      fs.rm(file, e => {
        if (e) {
          console.debug('file rm failed..');
          // return reject(false);
        }
        console.debug(`${file} is deleted.`);
        resolve(true);
      });
    } catch (error) {
      console.debug(error);
      reject(false);
    }
  });
}

module.exports.saveFile = saveFile;
module.exports.saveFileAsync = saveFileAsync;
module.exports.deleteFile = module.exports.deleteFileAsync = deleteFile;
